import { App, createApp } from 'vue'
import AppCom from './App.vue'
import '@/styles/reset.css'
import { routes, setupRouter } from '@/router'
import { setupStore } from '@/store'
import { setupGlobDirectives } from '@/directives'
import './public-path'
import { createRouter, createWebHistory, Router, RouterHistory } from 'vue-router'
import { registerGlobComp } from '@/components/registerGlobComp'
// @ts-ignore
export let router: Nullable<Router>
let instance: App<Element>
let history: RouterHistory
async function render(props: IRenderProps) {
  const { container } = props
  history = createWebHistory(window.__POWERED_BY_QIANKUN__ ? '/app-byqjh-card' : '/')
  router = createRouter({
    history,
    routes
  })
  const app = createApp(AppCom)
  // Configure store
  // 配置 store
  setupStore(app)
  // 注册全局组件
  registerGlobComp(app)

  // 配置路由
  setupRouter(app, router)
  // 注册全局指令
  setupGlobDirectives(app)
  app.mount(
    typeof container === 'string' ? container : (container.querySelector('#app') as Element)
  )
}
if (!window.__POWERED_BY_QIANKUN__) {
  await render({ container: '#app' })
}
// eslint-disable-next-line @typescript-eslint/adjacent-overload-signatures
export async function bootstrap() {
  console.log('vue app bootstraped')
}

export async function mount(props: any) {
  console.log('props from main framework', props.data)
  await render(props)
}

export async function unmount() {
  instance.unmount()
  if (instance._container) {
    instance._container.innerHTML = ''
  }
  router = null
  history.destroy()
}
